#! /bin/bash
###############################################################################
#
# pkgrip - create tarballs from installed Solaris packages
#
# Copyright (C) 2010, 2011 Yaakov Selkowitz
# Copyright (C) 2011 Charles Wilson
# Provided by the MinGW project <http://mingw.org/>
#
# mgwport is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mgwport is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with mgwport.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################

case "$(uname -s)" in
	SunOS) ;;
	*) "This script can only be run on a Solaris host" ; exit 1 ;;
esac

d=$(pwd)

pushd / > /dev/null

for p in $@
do
	echo -n "$p: "

	lst=
	pv=

	# Solaris 11 adds a new 'pkg' command alongside the traditional 'pkg*'
	# tools.  Packages installed with 'pkg' are seen as installed by the
	# 'pkg*' tools but without a file list.  Packages installed with 'pkgadd'
	# are not seen by 'pkg'.

	if hash pkg &> /dev/null
	then
		pv=$(pkg info $p 2> /dev/null | grep 'Version:' | sed -e 's/ *Version: *\([^,]*\).*/\1/')
	fi

	if test -z "$pv"
	then
		pv=$(pkginfo -l $p 2> /dev/null | grep 'VERSION:' | sed -e 's/ *VERSION: *\([^,]*\).*/\1/')
	fi

	if test -z "$pv"
	then
		echo "ERROR: package not found"
		continue
	fi

	if hash pkg &> /dev/null
	then
		lst=$(pkg contents $p 2> /dev/null)
	fi

	if test -z "$lst"
	then
		# make sure this is usable by an ordinary user w/o /usr/sbin in PATH
		lst=$(/usr/sbin/pkgchk -l $p | grep Pathname | sed -e 's|Pathname: */||g' 2> /dev/null)
	fi

	if test -z "$lst"
	then
		echo "ERROR: could not retrieve file list"
		continue
	fi

	# Solaris tar (package SUNWcs) is not GNU, does not accept -z or -j
	tar cf $d/${p////-}-$pv.tar \
		$(for f in ${lst}
		  do
			if test -r $f && test ! -d $f
			then
				echo $f
			fi
		  done) \
	&& gzip -9 $d/${p////-}-$pv.tar \
	&& echo "Success" \
	|| echo "ERROR: failed to create package"

done

popd > /dev/null
